package com.content.scaffold.common.utils;


import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 静态持有 Spring 上下文，用于在非 Spring 管理的类中获取 Bean
 *
 * @author xiaojl
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

    /**
     * -- GETTER --
     *  获取上下文
     */
    @Getter
    private static ApplicationContext applicationContext;

    /**
     * 注入上下文
     */

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringContextHolder.applicationContext = context;
    }

    /**
     * 获取 Bean（通过类型）
     */

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 获取 Bean（通过名称）
     */

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }
}
